<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------


/**
 * 部门类
 * @package  module/base/system
 * @author   allen.qiang
 */

class sysDepartment {
    /**
     * 递归查询所有部门数据
     * @param array $department_array 部门数据数组
     * @param int $parentID 上级id
     * @param int $rank 层级
     * @param int $departmentID 部门id
     * @return bool
     */
    public function searchDepartment( &$department_array, $parentID=0, $rank = -1, $departmentID=null ) {

        global $G_SHOP;

        if (is_null($departmentID)) {
            //根据父级id查询子级部门，顶部部门的parentID为0
            $search_sql = 'SELECT * FROM user_department WHERE parentID = ? ORDER BY sort ASC';
            $department_result_array =& $G_SHOP->DBCA->stmt_query( $search_sql, 'i', $parentID );
        } else {
            //根据部门id，查询该部门及下级部门的信息
            $search_sql = 'SELECT * FROM user_department WHERE departmentID = ? ORDER BY sort ASC';
            $department_result_array =& $G_SHOP->DBCA->stmt_query( $search_sql, 'i', $departmentID );
        }


        if (!$department_result_array) {
            return false;
        }

        ++$rank;

        foreach($department_result_array as &$department) {

            $department_array[$department->departmentID] = array(
                'departmentID' => $department->departmentID,
                'departmentName' => $department->departmentName,
                'parentID' => $department->parentID,
                'useFlg' => $department->useFlg,
                'rank' => $rank,
                'sort'=> $department->sort,
                'memo'=> $department->memo,
                'sub' => array()
            );

            //递归查询
            $this->searchDepartment($department_array[$department->departmentID]['sub'], $department->departmentID, $rank);

        }

        return false;

    }

    /**
     * 生成部门编辑页html代码
     */
    public function createDepartmentListHtml( $department_array, &$department_html ) {

        foreach($department_array as &$department) {

            $departmentID = $department['departmentID'];
            $rank = $department['rank'];
            $useFlg = $department['useFlg'];
            $sort = $department['sort'];
            $parentID = $department['parentID'];

            if ($department['rank'] == 0) {
                $department_html .= '<tr>';
            } else {
                $department_html .= '<tr class="deparment_line_' . $department['parentID'] . '" cid="' . $departmentID . '" style="display: none;">';
            }

            $department_html .= '<td>';
            if (!empty($department['sub'])) {
                $department_html .= '<div id="icon_' . $departmentID . '" onclick="userDepartment.showuserDepartment(' . $departmentID . ',' . $rank . ');" class="left closeImg" style="margin-left: ' . $department['rank'] * 30 . 'px;"></div>';
            } elseif ($department['rank'] > 0) {
                $department_html .= '<div class="left childImg" style="margin-left: ' . $department['rank'] * 30 . 'px;"></div>';
            } else {
                $department_html .= '<div class="left nopoint"></div>';
            }
            $department_html .= '<div class="left" >';
            $department_html .= '<form class="form-inline" role="form"><div class="form-group">';
            $department_html .= '<input  class="form-control input-sm "  id="input_' . $departmentID . '" type="text" value="' . $department['departmentName'] . '" width="20%"></div>';
            $department_html .= '<div class="form-group">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;排序&nbsp;&nbsp;&nbsp; <input id="sort_'.$departmentID.'" class="form-control input-sm " type="text" style="width:60px;"  maxlength="10" name="sort_10" value="' .$sort. '"></div>';

            $department_html .= '</form></div>';
            $department_html .= '</td>';

            $department_html .= '<td>';
            $department_html .= '<div class="form-group">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div class="editCategory" onclick="userDepartment.edit('.$departmentID.');" width="10px"></div></div>';
            $department_html .= '</td>';
            $department_html .= '<td  style="text-align:center;">';
            $department_html .= '<a onclick="userDepartment.changeUse('.$departmentID.','. $parentID . ',' .$useFlg. ');" href="javascript:void(0);">';
            if($useFlg == 1){
                $department_html .= '启用';
            } else {
                $department_html .= '禁用';
            }

            $department_html .= '</a>';
            $department_html .= '</td>';

            $department_html .= '<td style="text-align:center;">';
            $department_html .='<div class="big_f childCategory" onclick="userDepartment.add(' . $departmentID . ');"></div>';
            $department_html .= '</td>';

            $department_html .= '<td style="text-align:center;">';
                $department_html .='<div class="delcategory" onclick="userDepartment.delDepartment('. $departmentID .');"></div>';
            $department_html .= '</td>';

            $department_html .= '</tr>';

            if ($department['sub']) {
                $this->createDepartmentListHtml($department['sub'], $department_html);
            }

        }

    }

    /**
     * 生成部门select标签html代码
     */
    public function createDepartmentSelectOptionHtml($department_array, &$department_select_html) {
        foreach($department_array as &$department) {
            $departmentID = $department['departmentID'];
            $departmentName = $department['departmentName'];

            if($department['rank'] > 0){

                $department_select_html .= '<li class="left childSelectImg"  departmentID="'.$departmentID.'" style="margin-top:10px;margin-bottom:10px;margin-left: ' . $department['rank'] * 30 . 'px;" >&nbsp;&nbsp;' .$departmentName . '</li>';
            }else{
                $department_select_html .= '<li style="margin-top:10px;" departmentID="'.$departmentID.'">' .$departmentName . '</li>';
            }
//            if($department['rank'] > 0){
//                $department_select_html .= '<option class="left childSelectImg" style="margin-top:10px;margin-bottom:10px;margin-left: ' . $department['rank'] * 30 . 'px;" value="' . $departmentID . '">&nbsp;&nbsp;' .$departmentName . '</option>';
//            }else{
//                $department_select_html .= '<option style="margin-top:10px;" value="' . $departmentID . '">' .$departmentName . '</option>';
//            }

            if ($department['sub']) {
                $this->createDepartmentSelectOptionHtml($department['sub'], $department_select_html);
            }
        }
    }

    /**
     * 添加部门组织
     *
     */
    public function saveUserdepartment ( $arg_array ) {
        global $G_SHOP;

        //检查参数
        if (!isset($arg_array['creator'], $arg_array['departmentName'],$arg_array['sort'])){

            return array('message'=>'参数错误','code'=> 400);

        }

        $creator	  = $arg_array['creator'] ;				//创建或者修改者
        $parentID   = $arg_array['departmentID'] ;			//上级部门ID
        $departmentName = trim($arg_array['departmentName']) ;	//部门名称
        $memo	  = trim($arg_array['memo']) ;		//备注
        $sort = $arg_array['sort'];  //排序
        try{

            $userDepartment = new entity('user_department') ;
            $userDepartment->parentID = $parentID;
            $userDepartment->departmentName = $departmentName;

            if($G_SHOP->DBCA->fetch($userDepartment))
                throw new Exception('当前部门已存在,请检查后再操作', 400);

            //保存部门信息
            $userDepartment->creator = $creator;
            $userDepartment->departmentName =$departmentName;
            $userDepartment->parentID = $parentID;
            $userDepartment->memo = $memo;
            $userDepartment->sort = $sort;
            $userDepartment->useFlg = $_REQUEST['useFlg'];
            $G_SHOP->DBCA->save( $userDepartment ) ;

            return array( 'code' => 200, 'message' => '添加成功' ) ;

        }catch (Exception $e) {
            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
    }


    /*
    *
    * 递归改变启用状态方法
    */
    private function recursionChangeStat( $parentID, $useFlg ) {

        global $G_SHOP;

        //根据父级id查询子级部门，顶部部门的parentID为0
        $search_sql = 'SELECT * FROM user_department WHERE parentID =?  ORDER BY sort ASC';
        $department_result_array = $G_SHOP->DBCA->stmt_query( $search_sql, 'i', $parentID );

        if (!$department_result_array) {
            return false;
        }

        foreach($department_result_array as &$department) {

            //禁用/启用部门
            $change_department = new entity('user_department');
            $change_department->departmentID = $department->departmentID;
            $G_SHOP->DBCA->fetch($change_department);

            $change_department->useFlg = $useFlg;
            $G_SHOP->DBCA->save($change_department);

            //递归查询
            $this->recursionChangeStat( $department->departmentID, $useFlg );

        }

    }


    /*
     *
     * 改变禁用启用状态
     */
    public function changeStatue(){
        global $G_SHOP;

        //检查参数
        if (!isset($_REQUEST['departmentID'], $_REQUEST['useFlg'])) {
            echo json_encode(array('code' => 400, 'message' => '缺少参数' )) ;
            exit;
        }

        if (!in_array($_REQUEST['useFlg'], array(0, 1))) {
            echo json_encode(array('code' => 400, 'message' => '参数错误，请核实' )) ;
            exit;
        }

        $change_department = new entity('user_department');
        $change_department->departmentID = $_REQUEST['departmentID'];
        if (!$G_SHOP->DBCA->fetch($change_department)) {
            echo json_encode(array('code' => 400, 'message' => '部门信息未找到，请核实')) ;
            exit;
        }
        if($_REQUEST['useFlg'] == 1){
            $change_department->useFlg = 0;
        }else{
            $change_department->useFlg = 1;
        }

        try {

            //开启事务
            $G_SHOP->DBCA->beginTransaction();

            $G_SHOP->DBCA->save($change_department);

            //提交事务
            $G_SHOP->DBCA->commit();

            $this->recursionChangeStat( $change_department->departmentID, $change_department->useFlg );

            return array('code' => 200, 'message' => '部门状态更新成功');

        }catch (Exception $e){

            //事务回滚
            $G_SHOP->DBCA->rollBack();

            error_log($e->getMessage());

            return array('code' => 400, 'message' => '部门状态更新失败' ) ;
        }
    }

    /*
     *
     * 修改部门信息
     */
    public function editUserDepartment(){

        global $G_SHOP;

        //检查参数
        if (!isset($_REQUEST['departmentID'])) {
            return array('code' => 400, 'message' => '缺少参数' ) ;
        }


        $change_department = new entity('user_department');
        $change_department->departmentID = $_REQUEST['departmentID'];


        if (!$G_SHOP->DBCA->fetch($change_department)) {
            return array('code' => 400, 'message' => '部门信息未找到，请核实') ;
        }

        $change_department->departmentName = $_REQUEST['departmentName'];
        $change_department->sort = $_REQUEST['sort'];

        try {

            //开启事务
            $G_SHOP->DBCA->beginTransaction();

            $G_SHOP->DBCA->save($change_department);

            //提交事务
            $G_SHOP->DBCA->commit();

            return array('code' => 200, 'message' => '部门信息更新成功') ;

        }catch (Exception $e){

            //事务回滚
            $G_SHOP->DBCA->rollBack();

            error_log($e->getMessage());

            return array('code' => 400, 'message' => '部门信息更新失败' ) ;
        }
    }

 /*
 *
 * 递归删除部门方法
 */
    private function recursionDelStat( $parentID ) {

        global $G_SHOP;

        //根据父级id查询子级部门，顶部部门的parentID为0
        $search_sql = 'SELECT * FROM user_department WHERE parentID =?  ORDER BY sort ASC';
        $department_result_array = $G_SHOP->DBCA->stmt_query( $search_sql, 'i', $parentID );

        if (!$department_result_array) {
            return false;
        }

        foreach($department_result_array as &$department) {

            //删除部门
            $change_department = new entity('user_department');
            $change_department->departmentID = $department->departmentID;
            $G_SHOP->DBCA->fetch($change_department);

            $G_SHOP->DBCA->delete($change_department);

            //递归查询
            $this->recursionDelStat( $department->departmentID );

        }

    }

    /*
     *
     * 删除部门信息
     */
    public function delUserDepartment(){
        global $G_SHOP;

        //检查参数
        if (!isset($_REQUEST['departmentID'])) {
            return array('code' => 400, 'message' => '缺少参数' ) ;
        }

        $change_department = new entity('user_department');
        $change_department->departmentID = $_REQUEST['departmentID'];
        if (!$G_SHOP->DBCA->fetch($change_department)) {
            return array('code' => 400, 'message' => '部门信息未找到，请核实') ;
        }

        try {

            //开启事务
            $G_SHOP->DBCA->beginTransaction();

            $G_SHOP->DBCA->delete($change_department);

            //提交事务
            $G_SHOP->DBCA->commit();

            $this->recursionDelStat( $change_department->departmentID );

            return array('code' => 200, 'message' => '部门删除成功') ;

        }catch (Exception $e){

            //事务回滚
            $G_SHOP->DBCA->rollBack();

            error_log($e->getMessage());

            return array('code' => 400, 'message' => '部门删除失败' ) ;
        }
    }

    /**
     * 查询部门详情
     * @param int $departmentID 部门id
     * @return array|null
     */
    public function searchDepartmentDetail( $departmentID ) {

        global $G_SHOP;

        $search_sql = 'SELECT * FROM user_department WHERE departmentID = ?';
        $department_result_array = $G_SHOP->DBCA->stmt_query( $search_sql, 'i', $departmentID );
        if (!$department_result_array) {
            return null;
        }

        return array(
            'departmentID' => $department_result_array[0]->departmentID,
            'departmentName' => $department_result_array[0]->departmentName,
            'parentID' => $department_result_array[0]->parentID
        );

    }

    /**
     * 根据部门id查询上级部门id（针对营销部门换组织架构）
     * @param int $oldID 没有更改之前的部门id
     * @param int $newID 更改后的部门id
     * @param int $department 销售部所有信息
     * @return true|false
     * @author allen.qiang@fistforward.com
     */
    public function searchPdepartmentID($oldID,$newID,$department) {

        $oldPrentID='';
        $newPrentID='';
        if(is_array($department) && $oldID!=$newID){
            foreach($department as $key=>$value){
                if($this->deep_in_array($oldID, $value['sub'])){
                   $oldPrentID=$key;
                }
                if($this->deep_in_array($newID, $value['sub'])){
                   $newPrentID=$key;
                }
            }
            if($oldPrentID==$newPrentID){
                return true;
            }else{
                return false;
            }
        }else{
           return false; 
        }
    }
    /**
     * 查询某个值是否在多维数组里存在
     * @param int $value 部门id
     * @param array $array 部门数组
     * @return true|false
     * @author allen.qiang@fistforward.com
     */
     public function deep_in_array($value, $array) {   
        foreach($array as $item) {   
            if(!is_array($item)) {   
                if ($item == $value) {  
                    return true;  
                } else {  
                    continue;   
                }  
            }   
               
            if(in_array($value, $item)) {  
                return true;      
            } else if($this->deep_in_array($value, $item)) {  
                return true;      
            }  
        }   
        return false;   
     } 
}